package com.ruoyi.web.controller.tool;



import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 普通查询demo
 */
public class WuliuyunApi {

    private static final String hexDigIts[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    private static String url = "http://express.xuanquetech.com/express/v2/queryExpressRoutes";//请求路径
    private static String appId = "ac51d6ed43c344b78389c1ad0a06235a";//您的appid
    private static String appSecret = "aefd4e9ab98a4336af48cb093b0e9ded";//您的appSecret


    public static void main(String[] args) {
        String phone="02442885063";
        int num=phone.length();
        phone=phone.substring(num-4,num);
        System.out.println(phone);
        String r=getPostResult("SF0261713619057","SF","02442885063");
        System.out.println(r);
    }

    public static String getPostResult(String kddh, String com, String phone){
        int num=phone.length();
        phone=phone.substring(num-4,num);
        //请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        //组装参数
        String requestData = "{\"cpCode\":\""+com+"\",\"mailNo\":\""+kddh+"\",\"phone\":\""+phone+"\"}";
        Map<String, String> params = new HashMap();
        params.put("appid", appId);
        params.put("sign", getSign(appSecret, requestData));//签名
        params.put("requestData", requestData);
        String resultData = httpPostWithForm(url, params, headers);// 发送post请求并接收返回结果

        return resultData;
    }

    /**
     * 以form表单形式提交数据，发送post请求
     *
     * @param url
     * @param params
     * @param headers
     * @return
     */
    public static String httpPostWithForm(String url, Map<String, String> params, Map<String, String> headers) {
        // 用于接收返回的结果
        String resultData = "";
        try {
            HttpPost post = new HttpPost(url);
            //设置头部信息
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    post.setHeader(entry.getKey(), entry.getValue());
                }
            }
            List<BasicNameValuePair> pairList = new ArrayList<>();
            for (String key : params.keySet()) {
                pairList.add(new BasicNameValuePair(key, params.get(key)));
            }
            UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairList, "utf-8");
            post.setEntity(uefe);
            // 创建一个http客户端
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            // 发送post请求
            HttpResponse response = httpClient.execute(post);
            resultData = EntityUtils.toString(response.getEntity(), "UTF-8");// 返回正常数据
        } catch (Exception e) {
            System.out.println("接口连接失败 e:" + e);
        }
        return resultData;
    }

    /**
     * 加签
     *
     * @param appSecret   用户的appSecret
     * @param requestData json入参
     * @return 处理后，返回的签名值
     */
    public static String getSign(String appSecret, String requestData) {
        String signValue = requestData + appSecret;//按顺序将参数拼接起来 如：requestData+appSecret
        System.out.println("原参数拼接:" + signValue);
        String md5SignValue = MD5Encode(signValue, "utf8");//形成MD5加密后的签名
        System.out.println("MD5加密:" + md5SignValue);
        return md5SignValue;
    }

    /**
     * MD5加密
     *
     * @param origin      字符
     * @param charsetname 编码
     * @return
     */
    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (null == charsetname || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception e) {
        }
        return resultString;
    }


    public static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    public static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigIts[d1] + hexDigIts[d2];
    }

}

